/*
 * Copyright (C) 2014 Mestrelab Research S.L. All rights reserved.
 *
 * This file is part of the Mnova scripting toolkit.
 *
 * Authorized users of MNova Software may use this file freely, but this file is provided AS IS
 * with NO WARRANTY OF ANY KIND, INCLUDING THE WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS
 * FOR A PARTICULAR PURPOSE.
*/

/*globals mainWindow, NMRSpectrum, nmr, Application, Page, Utl, MnUi, mnMessage*/
/*jslint plusplus: true, indent: 4, white: true, sub: true*/

/*Automatically adds the traces to 2D experiments when possible.*/

function nmrAutoAttachTraces(aItemId) {
	'use strict';

	var actDoc = mainWindow.activeDocument,
		inputSpc = new NMRSpectrum(actDoc.getItem(aItemId)),
		nmrSpc,
		nmrCount = actDoc.itemCount('NMR Spectrum'),
		i = 0,
		nmrSpcObj = {'1D': {}, '2D': {}, '2DArr': []},
		page,
		nuc1 = '',
		nuc2 = '',
		acceptEvent = false,
		hasHorzTrace, hasVertTrace,
		funcSpcToType = function (aSpc) {
			switch (aSpc.dimCount) {
			case 1:
				nuc1 = aSpc.nucleus(false);
				if (!nmrSpcObj['1D'][nuc1]) {
					nmrSpcObj['1D'][nuc1] = [];
				}
				nmrSpcObj['1D'][nuc1].push(aSpc);
				break;
			case 2:
				hasHorzTrace = aSpc.getProperty('traces.horizontal.visible') && aSpc.getProperty('traces.horizontal.isExternal');
				hasVertTrace = aSpc.getProperty('traces.vertical.visible') && aSpc.getProperty('traces.vertical.isExternal');
				if ((hasHorzTrace && hasVertTrace) || nmrSpcObj['2D'][aSpc.experimentType]) {
					mnMessage("Previous trace detected");
					return false;
				}
				nmrSpcObj['2D'][aSpc.experimentType] = aSpc;
				nmrSpcObj['2DArr'].push(aSpc);
				break;
			default:
				return false;
			}
			return true;
		},
		set2DTraces = function (a2DSpc, aHTraceArr, aVTraceArr) {
			var ret = false,
				a2DPath = "", hasHorzTrace, hasVertTrace,
				sortFunc = function(aFirst, aSecond){
					var firstPath = aFirst.getParam("Data File Name"),
						firstDist = Utl.pathDistance(a2DPath, firstPath),
						secondPath = aSecond.getParam("Data File Name"),
						secondDist = Utl.pathDistance(a2DPath, secondPath);
					//print(firstPath);
					//print(secondPath);
					//print(firstDist, secondDist);
					return firstDist - secondDist;
				};
			if (a2DSpc) {
				a2DPath = a2DSpc.getParam("Data File Name");
				hasHorzTrace = a2DSpc.getProperty('traces.horizontal.visible') && a2DSpc.getProperty('traces.horizontal.isExternal');
				hasVertTrace = a2DSpc.getProperty('traces.vertical.visible') && a2DSpc.getProperty('traces.vertical.isExternal');
				if (aHTraceArr && !hasHorzTrace) { //don't replace the existing trace
					aHTraceArr = aHTraceArr.sort(sortFunc);
					//print(aHTraceArr);
					a2DSpc.setProperty('traces.horizontal.visible', true);
					a2DSpc.setTrace(aHTraceArr[0], true);
					mnDebug("Horizontal trace set");
					ret = true;
				} else if (hasHorzTrace) {
					mnMessage("Previous horizontal trace detected");
				}
				if (aVTraceArr && !hasVertTrace) {
					aVTraceArr = aVTraceArr.sort(sortFunc);
					a2DSpc.setProperty('traces.vertical.visible', true);
					a2DSpc.setTrace(aVTraceArr[0], false);
					mnDebug("Vertical trace set");
					ret = true;
				} else if (hasVertTrace) {
					mnMessage("Previous vertical trace detected");
				}
			}

			if (ret) {
				a2DSpc.update();
				page = new Page(a2DSpc.page);
				page.update();
			}
			return ret;
		};

	if (inputSpc === undefined || !inputSpc.isValid() || inputSpc.name !== 'NMR Spectrum') {
		return false;
	}

	if (!funcSpcToType(inputSpc)) {
		return false;
	}

	for (i = 0; i < nmrCount; ++i) {
		nmrSpc = new NMRSpectrum(actDoc.item(i, 'NMR Spectrum'));
		if (nmrSpc.isValid() && nmrSpc.uuid !== aItemId) {
			funcSpcToType(nmrSpc);
		}
	}

	for (i = 0; i < nmrSpcObj['2DArr'].length; ++i) {
		nuc1 = nmrSpcObj['2DArr'][i].nucleus(1, false);
		nuc2 = nmrSpcObj['2DArr'][i].nucleus(2, false);
		if (nmrSpcObj['1D'][nuc1] || nmrSpcObj['1D'][nuc2]) {
			acceptEvent =  set2DTraces(nmrSpcObj['2DArr'][i], nmrSpcObj['1D'][nuc2], nmrSpcObj['1D'][nuc1]) || acceptEvent;
		}
	}

	//print ("AcceptEvent: ", acceptEvent);
	return acceptEvent;
}

nmrAutoAttachTraces.run = function() {
	'use strict';

	nmrAutoAttachTraces(nmr.activeSpectrum().uuid);
};

if (this.MnUi && MnUi.scripts_nmr) {
	MnUi.scripts_nmr.scripts_nmr_AutoTraces = nmrAutoAttachTraces.run;
}
